#include "OLED_IIC.h"

sbit OLED_SCL = P2^1;
sbit OLED_SDIN = P2^0;

#define OLED_SCLK_Clr() OLED_SCL = 0
#define OLED_SCLK_Set() OLED_SCL = 1

#define OLED_SDIN_Clr() OLED_SDIN = 0
#define OLED_SDIN_Set() OLED_SDIN = 1

void OLED_IIC_Start();
void OLED_IIC_Stop();
void OELD_IIC_Wait_Ack();
void Write_OLED_IIC_Byte(unsigned char IIC_Byte);
void Write_OLED_IIC_Command(unsigned char IIC_Command);
void Write_OLED_IIC_Data(unsigned char IIC_Data);

/**
 * @brief start OLED IIC communication
 * 
 */
void OLED_IIC_Start()
{
	OLED_SCLK_Set();
	OLED_SDIN_Set();
	OLED_SDIN_Clr();
	OLED_SCLK_Clr();
}

/**
 * @brief stop OLED IIC communication
 * 
 */
void OLED_IIC_Stop()
{
	OLED_SCLK_Set();
	// OLED_SCLK_Clr();
	OLED_SDIN_Clr();
	OLED_SDIN_Set();
	
}

/**
 * @brief wait for OLED IIC ACK
 * 
 */
void OLED_IIC_Wait_Ack()
{
	OLED_SCLK_Set() ;
	OLED_SCLK_Clr();
}

/**
 * @brief write one byte to OLED IIC
 * 
 * @param IIC_Byte the byte to be written
 */
void Write_OLED_IIC_Byte(unsigned char IIC_Byte)
{
	unsigned char i;
	unsigned char m,da;
	da=IIC_Byte;
	OLED_SCLK_Clr();
	for(i=0;i<8;i++)		
	{
		m = da;
		//	OLED_SCLK_Clr();
		m = m & 0x80;
		if(m == 0x80)
		{
			OLED_SDIN_Set();
		}
		else 
		{
			OLED_SDIN_Clr();
		}
		da = da<<1;
		OLED_SCLK_Set();
		OLED_SCLK_Clr();
	}
}
/**
 * @brief write one command to OLED IIC
 * 
 * @param IIC_Command the command to be written
 */
void Write_OLED_IIC_Command(unsigned char IIC_Command)
{
    OLED_IIC_Start();
    Write_OLED_IIC_Byte(0x78);            //Slave address,SA0=0
	OLED_IIC_Wait_Ack();	
    Write_OLED_IIC_Byte(0x00);			//write command
	OLED_IIC_Wait_Ack();	
    Write_OLED_IIC_Byte(IIC_Command); 
	OLED_IIC_Wait_Ack();	
    OLED_IIC_Stop();
}

/**
 * @brief write one data to OLED IIC
 * 
 * @param IIC_Data the data to be written
 */
void Write_OLED_IIC_Data(unsigned char IIC_Data)
{
    OLED_IIC_Start();
    Write_OLED_IIC_Byte(0x78);			//D/C#=0; R/W#=0
	OLED_IIC_Wait_Ack();	
    Write_OLED_IIC_Byte(0x40);			//write data
	OLED_IIC_Wait_Ack();	
    Write_OLED_IIC_Byte(IIC_Data);
	OLED_IIC_Wait_Ack();	
    OLED_IIC_Stop();
}
